/*
 *
 * -------------------------------------------------------------------------------------------------
 *                            COPYRIGHT(C) BOCO HEALTH 2016
 * -------------------------------------------------------------------------------------------------
 *
 * =================================================================================================
 *  *HISTORY
 *
 *      Tag                Date            Author           Description
 * =================================================================================================
 *      created            2017/1/17      caodailu        create
 * =================================================================================================
 *
 *
 */

package com.boco.familyuser.view.custom_im;

import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.aop.Pointcut;
import com.alibaba.mobileim.aop.custom.IMConversationListUI;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.kit.contact.YWContactHeadLoadHelper;
import com.boco.familyuser.App;
import com.boco.familyuser.R;
import com.boco.familyuser.rxbus.RxBus;
import com.orhanobut.logger.Logger;
import com.zhy.autolayout.utils.AutoUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.boco.familyuser.view.main.MainActivity.START_CONTACTS;


public class ConversationListUICustom extends IMConversationListUI {

    private static final String TAG = "ConversationListUICustom";
    @BindView(R.id.head_left_text)
    TextView headLeftText;
    @BindView(R.id.head_center_text)
    TextView headCenterText;
    @BindView(R.id.head_right_text)
    TextView headRightText;

    private YWIMKit mIMKit;

    public ConversationListUICustom(Pointcut pointcut) {
        super(pointcut);
    }


    /**
     * 返回会话列表的自定义标题
     *
     * @param fragment
     * @param context
     * @param inflater
     * @return
     */
    @Override
    public View getCustomConversationListTitle(final Fragment fragment,
                                               final Context context, LayoutInflater inflater) {
        //TODO 重要：必须以该形式初始化customView---［inflate(R.layout.**, new RelativeLayout(context),false)
        // ］------，以让inflater知道父布局的类型，否则布局xml**中定义的高度和宽度无效，均被默认的wrap_content替代
        LinearLayout customView = (LinearLayout) inflater
                .inflate(R.layout.include_head_top, new RelativeLayout(context), false);
        ButterKnife.bind(this, customView);


        mIMKit = App.getYwimKit();
        headCenterText.setVisibility(View.VISIBLE);
        headCenterText.setText("会话列表");
        headCenterText.setTextColor(Color.WHITE);
        final String loginUserId = mIMKit.getIMCore().getLoginUserId();
        final String appKey = mIMKit.getIMCore().getAppKey();
        if (TextUtils.isEmpty(loginUserId) || TextUtils.isEmpty(appKey)) {
            headCenterText.setText("未登录");
        }else {
            headLeftText.setVisibility(View.VISIBLE);
            headRightText.setVisibility(View.VISIBLE);
            headLeftText.setText("全部已读");
            headRightText.setText("联系人");
        }


        AutoUtils.auto(customView);
        return customView;
    }

    @Override
    public boolean enableSearchConversations(Fragment fragment) {
        return true;
    }

    /***********
     * 以下是定制会话item view的示例代码
     ***********/
    //有几种自定义，数组元素就需要几个，数组元素值从0开始
    //private final int[] viewTypeArray = {0,1,2,3}，这样就有4种自定义View
    private final int[] viewTypeArray = {0};

    /**
     * 自定义item view的种类数
     *
     * @return 种类数
     */
    @Override
    public int getCustomItemViewTypeCount() {
        return viewTypeArray.length;
    }

    /**
     * 自定义item的viewType
     *
     * @param conversation
     * @return
     */
    @Override
    public int getCustomItemViewType(YWConversation conversation) {
        //todo 若修改 YWConversationType.Tribe为自己type，SDK认为您要在｛@link #getCustomItemView｝中完全自定义，针对群的自定义，如getTribeConversationHead会失效。
        //todo 该原则同样适用于 YWConversationType.P2P等其它内部类型，请知晓！

        String conversationId = conversation.getConversationId();
        Logger.e(conversation.getConversationType() + "======");
        Logger.e(conversationId + "======");
//        if (conversationId.contains(MainActivity.SYSTEM_REQ_CONVERSATION)) {
//
//            return viewTypeArray[0];
//        }
//        else if (conversation.getConversationType() == YWConversationType.P2P){
//            return viewTypeArray[1];
//        }
        //这里必须调用基类方法返回！！
        return super.getCustomItemViewType(conversation);
    }


    /**
     * 根据viewType自定义item的view
     *
     * @param fragment
     * @param conversation   当前item对应的会话
     * @param convertView    convertView
     * @param viewType       当前itemView的viewType
     * @param headLoadHelper 加载头像管理器，用户可以使用该管理器设置头像
     * @param parent         getView中的ViewGroup参数
     * @return
     */
    @Override
    public View getCustomItemView(Fragment fragment, YWConversation conversation, View convertView, int viewType, YWContactHeadLoadHelper headLoadHelper, ViewGroup parent) {
        if (viewType == viewTypeArray[0]) {

            // TODO: 2016/12/14 0014 自定义系统消息
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(fragment.getActivity());
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.custom_conversation_sysmsg_item, parent, false);
                holder.head = (ImageView) convertView.findViewById(R.id.head);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.unread = (TextView) convertView.findViewById(R.id.unread);
                holder.custom_tv = (TextView) convertView.findViewById(R.id.custom_tv);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            String name = "系统消息";

            headLoadHelper.setHeadView(holder.head, conversation);
            holder.name.setText(name);

            holder.unread.setVisibility(View.GONE);
            int unreadCount = conversation.getUnreadCount();
            if (unreadCount > 0) {
                holder.unread.setVisibility(View.VISIBLE);
                if (unreadCount > 99) {
                    holder.unread.setText("99+");
                } else {
                    holder.unread.setText(String.valueOf(unreadCount));
                }
            }

            return convertView;

        }

        return super.getCustomItemView(fragment, conversation, convertView, viewType, headLoadHelper, parent);
    }

    @OnClick({R.id.head_left_show, R.id.head_center_show, R.id.head_right_show})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_left_show:
                mIMKit.getConversationService().markAllReaded();
                break;
            case R.id.head_center_show:
                mIMKit.getLoginService().login(App.getLoginParam(), new
                        IWxCallback() {
                            @Override
                            public void onSuccess(Object... objects) {
                                Logger.e("百川登录成功");
                            }

                            @Override
                            public void onError(int i, String s) {
                                Logger.e("百川登录失败");
                            }

                            @Override
                            public void onProgress(int i) {

                            }
                        });
                break;
            case R.id.head_right_show:
                RxBus.getInstance().post(START_CONTACTS);
                break;
        }
    }

    private class ViewHolder {
        ImageView head;
        TextView name;
        TextView unread;
        TextView custom_tv;
    }


}